package com.marui.ch1.spin;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author marui
 * @date 21:30 2020/4/11
 * @since 1.0
 * 自定义一个自旋锁(循环+cas)
 */
public class CustomSpinLock {

    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    /**
     * 加锁
     */
    public void lock(){
        Thread thread = Thread.currentThread();
        while (!atomicReference.compareAndSet(null,thread)){

        }

    }

    /**
     * 解锁
     */
    public void unlock(){
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread,null);
        System.out.println(Thread.currentThread().getName()+"---------------解锁--------------------");
    }


    public static void main(String[] args) {

        CustomSpinLock customSpinLock = new CustomSpinLock();

        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                customSpinLock.lock();
                System.out.println(Thread.currentThread().getName()+"---------------加锁---------------");
                try {
                    //System.out.println(Thread.currentThread().getName()+"执行");
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    customSpinLock.unlock();
                }

            },"线程"+i).start();
        }
    }

}
